# coding: utf-8
import sys, os


sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
import numpy as np
import matplotlib.pyplot as plt
import pickle
from mnist_data import load_mnist
from functions import sigmoid, softmax


def get_data():
    (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
    return x_test, t_test


def init_network():
    with open("sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network


def predict(network, x):#network是一个字典
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']
    #x目前是一个（图片数，784）的数组，那么W1肯定是（
    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, W3) + b3
    y = softmax(a3)
    return y


x, t = get_data()
network = init_network()
accuracy_cnt = 0
#这种方法是相当于对每一条x的记录分别处理
'''
for i in range(len(x)):
    y = predict(network, x[i])
    p= np.argmax(y) # 获取概率最高的元素的索引
    if p == t[i]:
        accuracy_cnt += 1
'''
#分批次处理
batch_size=100
#在x中截出一块块100行的数组
for i in range(0, len(x), batch_size):
    batch_x = x[i:i+batch_size] #(100,6000)
    batch_t = t[i:i+batch_size] #(100,1)
    batch_y = predict(network, batch_x) #(100,10)
    p=np.argmax(batch_y, axis=1)    #(100)
    accuracy_cnt+=sum(p==batch_t)

print("Accuracy:" + str(float(accuracy_cnt) / len(x)))